﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

/*Our principal (credentials - which are your username and roles) 
 * is not stored plainly as part of our cookie 
 * (nor should it, since a user could modify their list of role-memberships), 
 * it needs to be generated for each request.
 */
using System.Security.Principal;
using System.Threading;
using UNDP_Projects.Data_Access;
using System.DirectoryServices;

namespace UNDP_Projects
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            //string cookieName = FormsAuthentication.FormsCookieName;
            //HttpCookie authCookie = Context.Request.Cookies[cookieName];

            //if (null == authCookie)
            //{
            //    //There is no authentication cookie.
            //    return;
            //}

            //FormsAuthenticationTicket authTicket = null;
            //try
            //{
            //    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            //}
            //catch (Exception ex)
            //{
            //    throw new Exception(ex.Message+" "+ex.StackTrace);
            //}

            //if (null == authTicket)
            //{
            //    //Cookie failed to decrypt
            //    return;
            //}

            //string[] userRole = new string[] { "Programme", "Administrator", "Project" };

            //FormsIdentity id = new FormsIdentity(authTicket);

            //GenericPrincipal principal = new GenericPrincipal(id, userRole);

            //Context.User = principal;

//===========================================================================================================
            //WORKING!!!!!!!!!!!!!!!!!!!!!!
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;

                        // Get the stored user data, i.e. the roles
                        string userData = ticket.UserData;
                        string[] userRole = userData.Split(new Char[] {','});

                        HttpContext.Current.User = new GenericPrincipal(id, userRole);
                        Thread.CurrentPrincipal = new GenericPrincipal(id, userRole);
                    }
                }
            }
//==========================================================================================================
            /*if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is WindowsIdentity)
                    {
                        using (UNDPEntities db = new UNDPEntities())
                        {
                            using (DirectoryEntry de = new DirectoryEntry("LDAP://so.undp.local"))
                            {
                                using (DirectorySearcher adSearch = new DirectorySearcher(de))
                                {
                                    //WindowsIdentity id = (WindowsIdentity)HttpContext.Current.User.Identity;

                                    char[] separator = new char[] { '\\' };
                                    string[] uName = User.Identity.Name.Split(separator);

                                    adSearch.Filter = "(sAMAccountName=" + uName[1] + ")";
                                    adSearch.PropertiesToLoad.Add("userPrincipalName");
                                    SearchResult result = adSearch.FindOne();

                                    DirectoryEntry dResult = result.GetDirectoryEntry();

                                    string uEmail = dResult.Properties["sAMAccountName"][0].ToString() + "@undp.org";
                                    //string uEmail = "shillingi@gmail.com";
                                    string roles;

                                    try
                                    {
                                        var userRole = (from data in db.users
                                                        where
                                                            data.user_email == uEmail
                                                        select new
                                                        {
                                                            data.roles,
                                                            data.active
                                                        }).FirstOrDefault();

                                        if (userRole.active == false)
                                        {
                                            return;
                                        }

                                        roles = userRole.roles.Trim();

                                        string[] RolesOfUser = roles.Split(new Char[] { ',' });

                                        //WHERE THE PROBLEM LIES!!!!
                                        //<<<SOLVED!!!!!!>>>
                                        WindowsIdentity id = (WindowsIdentity)HttpContext.Current.User.Identity;

                                        HttpContext.Current.User = new GenericPrincipal(id, RolesOfUser);
                                        Thread.CurrentPrincipal = new GenericPrincipal(id, RolesOfUser);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Login Error " + ex.Message + " " + ex.StackTrace);
                                        //Response.Redirect("~/AccessDenied.aspx", true);
                                    }

                                    //string[] RolesOfUser = roles.Split(new Char[] { ',' });

                                    ////WHERE THE PROBLEM LIES!!!!
                                    ////<<<SOLVED!!!!!!>>>
                                    //WindowsIdentity id = (WindowsIdentity)HttpContext.Current.User.Identity;

                                    //HttpContext.Current.User = new GenericPrincipal(id, RolesOfUser);
                                    //Thread.CurrentPrincipal = new GenericPrincipal(id, RolesOfUser);

                                }
                            }

                        }
                    }
                }
            }*/
//=========================================================================================================
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}